package 力扣91;

/**
 * @ClassName : Day4_394_字符串解码
 * @Author : 骆发茂
 * @Date: 2021/12/15 11:15
 * @Description : https://leetcode-cn.com/problems/decode-string/
 * https://leetcode-cn.com/problems/decode-string/solution/java-di-gui-si-lu-qing-xi-dai-ma-yi-dong-t6mn/
 * 递归,数组
 */
public class Day4_394_字符串解码_lc题解_没看懂 {
    class Solution {
        public String decodeString(String s) {
            if (onlyString(s)) {
                return s;
            }

            //索引
            int index = 0;
            //数
            int len = s.length();

            StringBuilder res = new StringBuilder();
            //索引max 小于 数  在string范围内
            while (index < len) {
                char ch = s.charAt(index);
                //如果是字母，就放入数组中，索引++
                if ('a' <= ch && ch <= 'z') {
                    res.append(ch);
                    index++;
                } else {
                    //如果不是字母，是除了字母之外的，比如数字，[，]
                    int num = 0;
                    //从字母索引之后开始记录了
                    int left = index;
                    int right = index;
                    //索引小于长度string范围内，并且如果是数字的话，右括号++
                    while (right < len && s.charAt(right) >= '0' && s.charAt(right) <= '9')
                        right++;
                    //Java substring() 方法获取子字符串
                    num = Integer.parseInt(s.substring(left, right));
                    left = right;
                    right++;
                    int leftP = 1;
                    while (leftP != 0) {
                        char temp = s.charAt(right);
                        if (temp == '[') {
                            leftP++;
                        } else if (temp == ']') {
                            leftP--;
                        }

                        if (leftP == 0)
                            break;
                        right++;
                    }

                    String smallFrac = decodeString(s.substring(left + 1, right));
                    for (int i = 0; i < num; i++)
                        res.append(smallFrac);

                    index = right + 1;
                }
            }

            return res.toString();
        }

        //like asdasdasdad  return true
        public boolean onlyString(String s) {
            //索引指向
            int index = 0;
            //超过索引+1，length-1=max索引
            //一直查找，如果遇到【】，说明不是纯字符串
            while (index != s.length()) {
                char ch = s.charAt(index);

                if (ch == '[' || ch == ']') {
                    return false;
                }
                index++;
            }

            return true;
        }
    }

}